<?php
namespace control;


class priceChangeClass extends adIndexClass
{
    private const title            = '价格变更申请';
    private const page             = 'priceChange';
    private const table            = 'price_change';
    private const tableKehu        = 'kehu';
    private const tableMaterial    = 'material';

    /**
     * 字段初始化
     */
    public function fieldInit(): array
    {
        $tr = [
            'orderNo'  => [
                'name'  => "单据编码",
                'width' => 150,
            ],
            'companyName' => [
                'name'  => "客户",
                'width' => 150,
            ],
            'code'  => [
                'name'  => '成品编码',
                'width' => 120,
            ],
            'name'  => [
                'name'  => '成品名称',
                'width' => 150,
            ],
            'startTime'         => [
                'name'  => '启动日',
                'width' => 150,
            ],
            'price'          => [
                'name'  => '调整前价格('. static::$unit . ')',
                'width' => 150,
            ],

            'newPrice'          => [
                'name'  => '调整后价格('. static::$unit . ')',
                'width' => 150,
            ],
            'recordDate'          => [
                'name'  => '单据日期',
                'width' => 150,
            ],
            'text'          => [
                'name'  => '备注',
                'width' => 150,
            ]
        ];
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "客户编码"   => text(array("name" => "orderNo")),
                    "客户名称"   => text(array("name" => "companyName")),
                    '产品编码'  => text(array("name" => "materialCode")),
                ],
                [
                    '产品名称'  => text(array("name" => "materialName")),
                    '规格型号'  => text(array("name" => "model")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*客户列表-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        $url    = root . "control/adIndex.html?cla=" . self::page;
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
//            $button .= "<span onclick=\"newIframe('" . self::page . "','edit',{})\" class='spanButton'>新增</span>\n";
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        //导入
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //查询结果
        $where = ' 1=1 ';
        $equal = [
            'coid' => self::$coid,
        ];
        // 客户搜索
        if ($this->post('orderNo') || $this->post('companyName')) {
            $kWhere = search([
                "="    => $equal,
                "like" => [
                    'orderNo'     => $this->post('orderNo'),
                    'companyName' => $this->post('companyName'),
                ],
            ]);
            $where  .= " AND `khid` IN (SELECT khid FROM `kehu` WHERE 1=1 $kWhere)  ";
        }
        // 物料搜索
        if ($this->post('materialCode') || $this->post('materialName') || $this->post('model')) {
            $mWhere = search([
                "="    => $equal,
                "like" => [
                    'code'  => $this->post('materialCode'),
                    'name'  => $this->post('materialName'),
                    'model' => $this->post('model'),
                ],
            ]);
            $where  .= " AND `materialId` IN (SELECT id FROM `material` WHERE 1=1 $mWhere)  ";
        }
        //生成查询语句
        $where                       .= search([
            "=" => $equal,
        ]);
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page                        = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        $url = root . "control/adIndex.html?cla=" . self::page;
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box"  => array("name" => "listId", "value" => $array['id']),
                "edit"    => ["title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"],
                "detail"  => ["title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"],
            );
            $kehu     = query(self::tableKehu, " khid = '$array[khid]' ");
            $material = query(self::tableMaterial, " id = '$array[materialId]' ");
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'orderNo':
                    case 'companyName':
                        $row[] = $kehu[$key];
                        break;
                    case 'code':
                    case 'name':
                    case 'model':
                    case 'unit':
                        $row[] = $material[$key];
                        break;
                    case 'price':
                        $row[] = self::lostZero($array['price'],'pricePrecision');
                        break;
                    case 'salePrice':
                        $row[] = self::lostZero($material['salePrice'],'pricePrecision');
                        break;
                    case 'agreedPrice':
                        $row[] = self::lostZero($array['agreedPrice'],'pricePrecision');
                        break;
                    case 'agreedDiscount':
                        $row[] = ($array['agreedDiscount'] > 0 ? ($array['agreedDiscount'] * 100) . '%' : 0);
                        break;
                    case 'dealPrice':
                        $row[] = self::lostZero($array['dealPrice'],'pricePrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . $this->js() . clear;
        return json_encode($json, 320);
    }

    public function js()
    {
        return <<<eof
<script>
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
       $('#priceChangeAddMx').hide()
       $("#materialName").html(res.data.name);
       $("[name='price']").val(res.data.salePrice);
       $("[name='materialId']").val(res.data.materialId);
    },'json');
}
function countPrice(e){
    let agreedPrice = Number($("[name='agreedPrice']").val());
    let agreedDiscount = Number($("[name='agreedDiscount']").val())/100;
    $("#dealPrice").html((agreedPrice*agreedDiscount).toFixed(2))
}
</script>
eof;
    }

    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        $id   = $this->get('id') ?: suiji();
        $info = query(self::table, " id = '" . $id . "' ");
        $name = materialClass::getName($info['materialId']);
        $button[] = [
            "name"  => "保存",
            "type"  => "点击事件",
            "title" => "保存为草稿",
            'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];
        $kehu     = query(self::tableKehu, " khid = '$info[khid]' ");
        //表单
        $data['button'] = $this->tableShowButton($button);
        $body           = $this->edit4([
            '基本信息' => [
                [
                    must . "单据日期：" => text(["name" => "recordDate", 'class' => 'text', 'laydate' => [], "value" => $info['recordDate'] ?: $this->date]),
                    must . "客户："   => componentClass::selectText([
                        'name'   => 'khid',
                        'value'  => $info['khid'],
                        'title'  => $kehu['companyName'],
                        'cla'    => 'saleOrder',
                        'fun'    => 'getClient',
                        'change' => 'getContract',
                    ]),
                    "合同："          =>
                        selectMultiple([
                            "name"     => "contractId",
                            "value"    => $info['contractId'],
                            'table'    => "sales_contract",
                            'where'    => "clientId = '$info[khid]' and state = '已通过'",
                            'sqlId'    => 'id',
                            'sqlField' => 'name',
                            'title'    => '请选择',
                        ])  ,
                ],
                [
                    must . "物料：" => "<span id='materialName' class='exceed-ellipsis' style='max-width: 90%;'>$name</span>&nbsp;<span class='del-row-button' onclick=\"layer('{$this->get('cla')}','addMx',{})\">选择</span>" . hidden(array('name' => 'materialId', 'value' => $info['materialId'])),
                    "执行日期：" => text(["name" => "startTime", 'class' => 'text', 'laydate' => [], "value" => $info['startTime'] ?: $this->date]),
                    "调整前价格：" => text(["name" => "price", "id"=>'price', 'class' => 'text', "value" => $info['price']]),
                ],
                [
                    "现执行价格：" => text(["name" => "newPrice", 'class' => 'text', "value" => $info['newPrice']]),
                    "备注：" => textarea(["name" => "text", 'class' => 'text', "value" => $info['text']]),
                ],
            ]
        ]);
        $data['html'] = $this->pageEdit([
                "html"   => $body,
                'hidden' => hidden(['name' => 'id', 'value' => $id]),
            ]). $this->js();
        //返回
        return $this->tab($data);
    }

    public function editEdit()
    {
        $id         = $this->post('id') ?: self::getId();
        $field      = [
            "recordDate" => $this->post('recordDate'),
            "khid" => $this->post('khid'),
            "contractId" => $this->post('contractId'),
            "materialId" => $this->post('materialId'),
            "startTime" => $this->post('startTime'),
            "text" => $this->post('text'),
            "price" => $this->post('price') ? self::formattingFigure($this->post('price'), 'pricePrecision') : 0,
            "newPrice" => $this->post('newPrice') ? self::formattingFigure($this->post('newPrice'), 'pricePrecision') : 0,
            'updateTime' => $this->time,
            'state' => '草稿',
        ];
        $annotation = [
            'khid' => '客户',
            'materialId' => '物料',
        ];
        $rules      = [
            'khid' => 'required',
            'materialId' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info  = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::total(array(
                'table' => self::table,
                'where' => "materialId = '$field[materialId]' and khid = '$field[khid]' and coid = '" . self::$coid . "'  and id !='$id'"
            )) > 0) {
            $json['warn'] = '此客户已存在此物料的价格';
        } else {
            if (!$info['id']) {
                $orderNo = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'BGJG' . date('Ymd', strtotime($field['recordDate'])),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => " and coid = '" . self::$coid . "'",
                ], $field);
                $field        = array_merge($field, [
                    'id'   => $id,
                    'coid' => self::$coid,
                    'stid' => $this->control['stid'],
                    'orderNo' => $orderNo,
                    'unit' => '',
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "where" => $where,
                    "field" => $field,
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data   = [
                "id" => $info['id'],
            ];
            $button = [];
            $button = array_merge($button, $this->auditButton($info));

            if ($info['state'] == '草稿') {
                if ($this->power(self::page, "edit")) {
                    //按钮
                    $button[] = [
                        "name"  => "编辑",
                        "type"  => "顶部页卡",
                        "title" => "编辑信息",
                        "url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],

                    ];
                }
                if ($this->power(self::page, "del")) {
                    //按钮
                    $button[] = [
                        "name" => "删除",
                        "type" => "弹出层",
                        "cla"  => $this->get('cla'),
                        "fun"  => "operate",
                        "post" => ["act" => 'del', "id" => $info['id']],
                    ];
                }
            }
            if ($this->power(self::page, "cancel") && $info['state'] != '草稿' && !$info['isClose']) {
                $button[] = [
                    "name" => "撤回",
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }
            //操作记录
            $button[] = self::operateLogBut($info['id'], 1);
            $name = materialClass::getName($info['materialId']);
            $kehu           = query('kehu', "khid = '$info[khid]'");
            $sales_contract = query('sales_contract', "id = '$info[contractId]'");

            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html']   = $this->tableShow([
                '基本信息' => [
                    [
                        "单据日期：" => self::null($info['recordDate']),
                        "客户：" => $kehu['companyName'],
                        "合同：" => $sales_contract['name'],
                    ],
                    [
                        "物料：" => "<span id='materialName' class='exceed-ellipsis' style='max-width: 90%;'>$name</span>&nbsp;",
                        "价格调整启动日：" => self::null($info['startTime']),
                        "调整前价格：" => $info['price'],
                    ],
                    [
                        "调整后价格：" => $info['newPrice'],
                        "状态" => $info['state'] . self::operateRecord($info['id']),
                        "备注：" => pre($info['text']),
                    ],
                ],
                '流程' => [
                    [
                        auditClass::auditRecord(self::table, $info['id'])
                    ],
                ],
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 操作记录
     */
    public static function operateRecord($id): string
    {
        $result = find(['table' => 'auditing_follow', 'where' => "typeId = '$id' order by time desc"]);
        $li     = '';
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                $li .= "<li>{$array['text']}&emsp;{$array['time']}</li>";
            }
        }
        if (empty($li)) {
            $li = "<li>暂无记录</li>";
        }
        return "&emsp;<span class='del-row-button' id='record'>操作记录<div class='stateBlock operate-content'><ul>$li</ul></div></span>";
    }

    /**
     * 审核按钮
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
        if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => ["act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'name' => self::title,
                    'table' => self::table,
                    'process' => [
                        // 预览函数
                        'detail' => [
                            'cla' => $this->get('cla'),
                            'fun' => 'detail'
                        ],
                        //执行发起时验证函数
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
// 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => ["act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿', '已通过'],
                    ],
                    // 审核时回调
                    'process' => [
                        //执行首次审核时验证
                        'before' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                        //执行末次审核后处理
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun'=>'',
                        ],
                    ],
                ], 320))],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table
                ], 320))],
            ];
        }
        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] == '审核中') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => ["act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                    'table' => self::table,
                    // 当前状态
                    'state' => $info['state'],
                    // 变更
                    'field' => ['state'],   //变更字段 可多个
                    'value' => [
                        'state' => ['草稿'],
                    ],
                    'process' => [
                        //完成发起后执行函数
                        'after' => [
                            'cla' => $this->get('cla'),
                            'fun' => ''
                        ],
                    ],
                ], 320))],
            ];
        }
        return $button;
    }

    // 操作中转
    public function operate(): bool|string
    {
        $act  = $this->post('act') ?? '';
        $pwd  = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            default:
                $act      = 'del';
                $msg      = '删除' . self::title;
                $title    = '执行此操作将会永久删除所选的信息,删除后将无法找回，您确定要这么做吗？';
                $function = 'delete';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                $word = true;
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete(): bool|string
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = "删除成功";
                $x++;
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * @return bool|string
     */
    public function addMx()
    {
        $html   =
            materialClass::typeSelect(name: 'type').
            text(array("name" => "code", "title" => "产品编码")) .
            text(array("name" => "materialName", "title" => "产品名称")) .
            text(array("name" => "model", "title" => "规格型号"));
        $button = "<input style='margin-left: 5px' onclick=\"addRow()\" type='button' class='searchSub' value='提交'>";
        $html   = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "zindex" => 3, "html" => $html, "button" => $button));
    }

    /**
     *添加产品
     */
    public function addMxSearch()
    {
        $like        = [
            'a.name'          => $this->post('materialName'),
            'code'            => $this->post('code'),
            'model'           => $this->post('model'),
            'a.supplyControl' => '允许销售',
            'a.typePath' => $this->post('type'),
        ];
        $equal       = [
            'a.coid'   => self::$coid,
            'a.state'  => '启用',
        ];
        $where       = search(["like" => $like, "=" => $equal]);
        $page        = $this->page([
            "table"   => "material as a",
            "field"   => "a.*",
            "where"   => $where,
            'pageNum' => 50,
            "order"   => "a.`time` ASC",
        ]);
        $materialObj = new materialClass();
        //获取表头
        $tr[]     = ['', '分类', '产品编码', '产品名称', '规格型号'];
        //获取记录
        foreach ($page['array'] as $array) {
            $checkBox = "<input name='mxId' value='$array[id]' type='radio'>";
            $tr[]     = array(
                $checkBox,
                $materialObj::getTypePath($array['typeId']),
                $array['code'],
                $array['name'],
                $array['model']
            );
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxId = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxId)) {
            $json['warn'] = '请选择产品';
        } else {
            $material = query('material',"id = '$mxId'");
            $json['data'] = [
                'materialId' => $material['id'],
                'name'          => materialClass::getName($material['id']),
                'salePrice'=> self::lostZero($material['salePrice'],'pricePrecision')
            ];
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

}